<?php


namespace app\api\controller;


use app\common\controller\Api;
use app\common\model\Cardxamines;
use app\common\model\GoodsTag;
use app\common\model\Hospital;
use app\common\model\UserCards;
use http\Message\Body;
use think\Db;

class Distance extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';

    /**
     * 获取距离
     */
    public function getLat($address)
    {
        $address =$this->myTrim($address);
        //PhVDxS3C2sevmKP9GOU6zfB0MKadW0
        $key='456BZ-M7VWL-CUNPQ-MHRZW-P2LUE-5SBLJ';
        $sk = 'XuUCHWTFLnjO0riCyxd0wafhXMIIPPeh';
        //这里用的是地址解析api，获取指定地址经纬度
        $sig = md5("/ws/geocoder/v1?address=$address&key=$key".$sk);
        $url = 'https://apis.map.qq.com/ws/geocoder/v1?address='.$address.'&key='.$key.'&sig='.$sig;
        $data_info=$this->curl($url);
        $data_info = json_decode($data_info, true); //数据转换
        return $data_info;
    }
    function myTrim($str)
    {
        $search = array(" ","　","\n","\r","\t");
        $replace = array("","","","","");
        return str_replace($search, $replace, $str);
    }

    function curl($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        //参数为1表示传输数据，为0表示直接输出显示。
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //参数为0表示不带头文件，为1表示带头文件
        curl_setopt($ch, CURLOPT_HEADER,0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,false);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    public function getCurrentCity()
    {
        $lat =$this->request->param('lat');
        $lng=$this->request->param('lng');
        $time =time();
        $address= db('location_address')->where(['lat'=>$lat,'lng'=>$lng])->find();
        if($address){
            $data=['city'=>$address['city'],
                'province'=>$address['province'],
                'address'=>$address['address'],
                'district'=>$address['district']
                ];
            if($this->auth->isLogin()){
               $user_address= db('user_location_address')->where(['user_id'=>$this->auth->id])->order(['createtime'=>'desc'])->find();
               if($user_address){
                   if($user_address['lat']!=$address['lat']||$user_address['lng']!=$address['lng']){
                       $user_saves=$address;
                       $user_saves['user_id']=$this->auth->id;
                       $user_saves['createtime']=$time;
                       $user_saves['updatetime']=$time;
                       unset($user_saves['id']);
                       db('user_location_address')->insertGetId($user_saves);
                   }
               }else{
                   $user_saves=$address;
                   $user_saves['user_id']=$this->auth->id;
                   $user_saves['createtime']=$time;
                   $user_saves['updatetime']=$time;
                   unset($user_saves['id']);
                   db('user_location_address')->insertGetId($user_saves);
               }
            }

          $this->success('',$data);
        }else{
            $key=config('weixin.ak');
            $sk =config('weixin.sk');
            //这里用的是地址解析api，获取指定地址经纬度
            $sig = md5("/ws/geocoder/v1?location='.$lat.','.$lng.'&key=$key".$sk);
            $url = 'https://apis.map.qq.com/ws/geocoder/v1?location='.$lat.','.$lng.'&key='.$key.'&sig='.$sig;
            $data_info=$this->curl($url);
            $m = json_decode($data_info, true); //数据转换
            //  $url = "https://apis.map.qq.com/ws/geocoder/v1/?location=$lat,$lng&key="."腾讯地图申请key值"."&get_poi=1";
            // $data_info=$this->curl($url);
            //  $data_info = json_decode($data_info, true); //数据转换
            // dump($m);
            if(!empty($m))
            {
                if($m['status']==0){
                    if($m['result']['address']){
                        $address_component=$m['result']['address_component'];
                        $province_id=db('marea')->where(['name'=>$address_component['province'],'pid'=>0])->value('id');
                        $city_id=db('marea')->where(['name'=>$address_component['city'],'pid'=>$province_id])->value('id');
                        $saves= ['city'=>$address_component['city'],
                            'city_id'=>$city_id,
                            'province'=>$address_component['province'],
                            'province_id'=>$province_id,
                            'district'=>$address_component['district'],
                            'district_id'=>db('marea')->where(['name'=>$address_component['district'],'pid'=>$city_id])->value('id'),
                            'address'=>$m['result']['address']
                        ];
                        $msaves=$saves;
                        $msaves['lat']=$lat;
                        $msaves['lng']=$lng;
                        $msaves['street']=$address_component['street'];
                        $msaves['street_number']=$address_component['street_number'];
                        $msaves['createtime']=$time;
                        $msaves['updatetime']=$time;
                        db('location_address')->insertGetId($msaves);
                        if($this->auth->isLogin()){
                            $msaves1=$msaves;
                            $msaves1['user_id']=$this->auth->id;
                            db('user_location_address')->insertGetId($msaves1);
                        }
                        $this->success('',$saves);
                    }

                    $this->error('地址获取失败');
                }else{
                    $this->error($m['message']);
                }

            }else{
                $this->error('地址有误');
            }
        }


    }



   public function  getHospitals()
    {

        $parma= $this->request->param('');
        $lat = $this->request->param('lat');
        $lng = $this->request->param('lng');
        if (empty($lat)) $lat = 39.908515;
        if (empty($lng)) $lng = 116.437039;
        $where=[];
        $tags_id =$this->request->param('tags_id','');
        $district=$this->request->param('district','');
        if (!empty($district)){
            if($district!='全部'){
                $district_id=db('marea')->where(['name'=>$district,'level'=>3])->value('id');
                $where['area_id']=$district_id;
            }else{
                $city=$this->request->param('city','');
                $city_id=db('marea')->where(['name'=>$city,'level'=>2])->value('id');
                $where['city_id']=$city_id;
            }

            //  $where['_string'] = "getDistance(lng, lat, {$lng}, {$lat})<{$distance}";
        }else{
            $city=$this->request->param('city','');
            $city_id=db('marea')->where(['name'=>$city,'level'=>2])->value('id');
            $where['city_id']=$city_id;
        }
        $hospitals  =Hospital::field("*, getDistance(lng, lat, {$lng}, {$lat}) as distance")
            ->where(['status'=>1])
            ->where($where);
        if(!empty($tags_id)){
            $tags_name=Cardxamines::where(['id'=>$tags_id])->value('tag_name');

            $tags_ids=(new GoodsTag())->where(['tag_name'=>$tags_name,'way'=>2])->value('id');

            $hospitals->where('find_in_set(:id,tag_ids)',['id'=>$tags_ids]);


        }


      $data=   $hospitals->order(['distance'=>'asc','weigh'=>'desc','id'=>'desc'])
            ->paginate();
        foreach ($data as $k=>$v){

            if($v['distance']<1000){
                $data[$k]['distance']=ceil($v['distance']).'m';
            }else{
                $data[$k]['distance']=round($v['distance']/1000,2).'km';
            }

        }
        $this->success('',$data);
    }
}